﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using Microsoft.Win32;
using System.IO;

namespace EasyTrader.Form
{
    using PriceWaveList = List<EasyTrader.Wave.PriceWave>;
    using PricePointList = List<EasyTrader.Wave.PricePoint>;
    using PriceSignalList = List<EasyTrader.Signal.PriceSignal>;

    using DataItemList = List<EasyTrader.DataSet.BarDataItem>;
    using CodeList = List<EasyTrader.DataSet.CodeTable>;
    using BarTableList = List<EasyTrader.DataSet.BarDataTable>;
    using DDEDataList = List<EasyTrader.Option.DDEData>;
    using SimpleDataList = List<EasyTrader.DataSet.SimpleData>;

    public partial class FutureSystemFrm : System.Windows.Forms.Form
    {
        private string m_SysName = "";
        public string SysName
        {
            get { return m_SysName; }
            set { m_SysName = value; }
        }
        private int m_SysType = GlobalVar.SysTypeJisuWaveHogaSummit;
        public int SysType
        {
            get { return m_SysType; }
            set { m_SysType = value; }
        }

        private string m_HashCode = "";
        public string HashCode
        {
            get { return m_HashCode; }
            set { m_HashCode = value; }
        }
        
        private EasyTrader.Order.OrderManager m_ETOrderManager = null;
        public EasyTrader.Order.OrderManager ETOrderManager
        {
            get { return m_ETOrderManager; }
            set { m_ETOrderManager = value; }
        }


        private EasyTrader.Signal.WaveSignalManager m_WaveSignalManager = new EasyTrader.Signal.WaveSignalManager();
        public EasyTrader.Signal.WaveSignalManager WaveSignalManager
        {
            get { return m_WaveSignalManager; }
            set { m_WaveSignalManager = value; }
        }

        private EasyTrader.Signal.TotalSignalManager m_TotalSignalManager = null;
        public EasyTrader.Signal.TotalSignalManager TotalSignalManager
        {
            get { return m_TotalSignalManager; }
            set { m_TotalSignalManager = value; }
        }



        public FutureSystemFrm()
        {
            InitializeComponent();
        }

        public void UncheckAutoOrder()
        {
            cbAutoOrder.Checked = false;
        }

        public void UncheckAutoOrder(bool a_LastSignalFired, int a_SysType)
        {
            // 이벤트를 보낸 시스템과 현재 선택되어 있는 시스템이 일치하면 자동 주문을 체크를 해제해 준다.
            if (a_SysType == m_SysType)
            {
                if (cbAutoOrder.Checked == true)
                    cbAutoOrder.Checked = false;
                System.Windows.Forms.MessageBox.Show(GlobalVar.OrderEndedMsg);
            }
        }


        public void SysManager_OnLastSignalFired(object sender, EventArgs e)
        {
            EasyTrader.SysManagerEventArgs arg = (EasyTrader.SysManagerEventArgs)e;
            UncheckAutoOrder(arg.AutoOrder, arg.SysType);
        }

        private bool FileDeleted = false;

        private void DeleteKosip200File()
        {
            if (FileDeleted == true)
                return;

            string fileName = GlobalVar.K200Dir;
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            FileDeleted = true;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            timer.Start();
            DeleteKosip200File();
        }

        private bool m_ShowOption = true;

        int curChartType = 0;
        // Wave Manager
        private EasyTrader.Wave.WaveManager m_WaveManager = new EasyTrader.Wave.WaveManager();
        public EasyTrader.Wave.WaveManager WaveManager
        {
            get { return m_WaveManager; }
            set { m_WaveManager = value; }
        }

        // Cybos Plus Data Set Member
        private ETDataSet m_CPDataSet = null;
        public EasyTrader.ETDataSet CPDataSet
        {
            get { return m_CPDataSet; }
            set { m_CPDataSet = value; }
        }
        private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        private void InitTimer()
        {
            timer.Interval = GlobalVar.ChartRefreshInterval;
            timer.Tick += new EventHandler(OnTimerTick);
        }

        private void SetWaveOnChart(PriceWaveList a_WaveList)
        {
            // 먼저 이전에 모든 점들을 없애 준다.
            FutureSystemChartCtrl.Series["파동"].Points.Clear();
            for (int i = 0; i < a_WaveList.Count; i++)
            {
                EasyTrader.Wave.PriceWave wave = a_WaveList[i];
                //if (i == 0 && wave.Height() < GlobalVar.MinMainWaveHeight)
                //    continue;
                FutureSystemChartCtrl.Series["파동"].Points.AddXY(wave.StartX, wave.StartY);
                //FutureSystemChartCtrl.Series["파동"].Points[i].AxisLabel = wave.StartPoint.XValue.ToString();
                // 파동은 마지막 점을 한번 더 넣어 준다.
                if (i == a_WaveList.Count - 1)
                {
                    FutureSystemChartCtrl.Series["파동"].Points.AddXY(wave.EndX, wave.EndY);
                    //newSeries.Points[i + 1].AxisLabel = wave.EndPoint.XValue.ToString();
                }
            }
        }
        private bool ChartSaved = false;
        private void SaveChartImage()
        {
            DateTime now = DateTime.Now;
            if (now.Hour == 15 && now.Minute == 16 && ChartSaved == false)
            {
                string fileName = now.Year.ToString() + "_";
                fileName += now.Month.ToString() + "_";
                fileName += now.Day.ToString();
                fileName += m_SysName;
                fileName += ".jpg";
                string path = Directory.GetCurrentDirectory();
                path += "\\" + fileName;

                // 기존 파일이 있으면 지워준다.
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                FutureSystemChartCtrl.SaveImage(path, ChartImageFormat.Jpeg);
                ChartSaved = true;
            }
        }

        public void SaveChartImage(string a_GivenName)
        {
            DateTime now = DateTime.Now;
            string fileName = now.Year.ToString() + "_";
            fileName += now.Month.ToString() + "_";
            fileName += now.Day.ToString();
            fileName += a_GivenName;
            fileName += ".jpg";
            string path = Directory.GetCurrentDirectory();
            path += "\\" + fileName;

            // 기존 파일이 있으면 지워준다.
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            FutureSystemChartCtrl.SaveImage(path, ChartImageFormat.Jpeg);
        }

        private void SetSignalWaveOnChart(EasyTrader.Wave.PriceWave a_Wave)
        {
            if (a_Wave == null)
                return;
            // 먼저 이전에 모든 점들을 없애 준다.
            FutureSystemChartCtrl.Series["기상위"].Points.Clear();
            FutureSystemChartCtrl.Series["기하위"].Points.Clear();
            double max = Math.Max(a_Wave.StartY, a_Wave.EndY);
            double min = Math.Min(a_Wave.StartY, a_Wave.EndY);
            double high = max - GlobalVar.SignalWaveHeight * GlobalVar.StandardWaveHighLowPercent;
            double low = min + GlobalVar.SignalWaveHeight * GlobalVar.StandardWaveHighLowPercent;
            
            FutureSystemChartCtrl.Series["기상위"].Points.AddXY(a_Wave.StartX, high);
            FutureSystemChartCtrl.Series["기상위"].Points.AddXY(a_Wave.EndX, high);

            FutureSystemChartCtrl.Series["기하위"].Points.AddXY(a_Wave.StartX, low);
            FutureSystemChartCtrl.Series["기하위"].Points.AddXY(a_Wave.EndX, low);
        }

        private void SetSignalWaveOnChart(EasyTrader.Wave.PriceWave a_Wave, double a_HighVal, double a_LowVal)
        {
            if (a_Wave == null)
                return;
            // 먼저 이전에 모든 점들을 없애 준다.
            FutureSystemChartCtrl.Series["기상위"].Points.Clear();
            FutureSystemChartCtrl.Series["기하위"].Points.Clear();
            
            FutureSystemChartCtrl.Series["기상위"].Points.AddXY(a_Wave.StartX, a_HighVal);
            FutureSystemChartCtrl.Series["기상위"].Points.AddXY(a_Wave.EndX, a_HighVal);

            FutureSystemChartCtrl.Series["기하위"].Points.AddXY(a_Wave.StartX, a_LowVal);
            FutureSystemChartCtrl.Series["기하위"].Points.AddXY(a_Wave.EndX, a_LowVal);
        }

        private void SetSignalHeightOnChart(EasyTrader.Signal.ForecastingInfo a_ForeInfo, EasyTrader.Signal.HighLowInfo a_HighLowInfo)
        {
            if (a_ForeInfo == null || a_HighLowInfo == null)
                return;
            // 먼저 이전에 모든 점들을 없애 준다.
            FutureSystemChartCtrl.Series["기상위"].Points.Clear();
            FutureSystemChartCtrl.Series["기하위"].Points.Clear();
            
            double highLimit = 0.0;
            double lowLimit = 0.0;
            double firstHighY = 0.0;
            double firstLowY = 0.0;
            double secondLowY = 0.0;
            double secondHighY = 0.0;
            double lowRootLimit = a_HighLowInfo.LowY + GlobalVar.WaveRootLimit;
            double highRootlLimit = a_HighLowInfo.HighY - GlobalVar.WaveRootLimit;
            if (a_HighLowInfo.MinMaxHeight() >= GlobalVar.MaxCloseHeight)
            {
                firstHighY = a_HighLowInfo.HighY - GlobalVar.MinHighLowTransHeight;
                firstLowY = a_HighLowInfo.LowY + GlobalVar.MinHighLowTransHeight;
                secondHighY = a_HighLowInfo.CloseMax - GlobalVar.MinCloseTransHeight;
                secondLowY = a_HighLowInfo.CloseMin + GlobalVar.MinCloseTransHeight;
            }
            else
            {
                firstHighY = a_HighLowInfo.HighY - GlobalVar.MinHighLowHeight;
                firstLowY = a_HighLowInfo.LowY + GlobalVar.MinHighLowHeight;
                secondHighY = a_HighLowInfo.CloseMax - GlobalVar.MinCloseHeight;
                secondLowY = a_HighLowInfo.CloseMin + GlobalVar.MinCloseHeight;
            }

            lowLimit = Math.Max(firstLowY, secondLowY);
            highLimit = Math.Min(firstHighY, secondHighY);

            FutureSystemChartCtrl.Series["기상위"].Points.AddXY(a_ForeInfo.StartX, highLimit);
            FutureSystemChartCtrl.Series["기상위"].Points.AddXY(a_ForeInfo.EndX, highLimit);

            FutureSystemChartCtrl.Series["기하위"].Points.AddXY(a_ForeInfo.StartX, lowLimit);
            FutureSystemChartCtrl.Series["기하위"].Points.AddXY(a_ForeInfo.EndX, lowLimit);
        }

        private void InitControl()
        {
            for (int i = 0; i < GlobalVar.SysNameArray.Length; i++)
                comboSystem.Items.Add(GlobalVar.SysNameArray[i]);
            comboSystem.SelectedIndex = m_SysType;
            comboFirstSignal.SelectedIndex = 0;

            cbShowOption.Checked = true;

            FutureSystemChartCtrl.Series["지수"].ToolTip = "#VALX : #VAL";
            FutureSystemChartCtrl.Series["파동"].ToolTip = "#VALX : #VAL";
            FutureSystemChartCtrl.Series["최고"].ToolTip = "#VALX : #VAL";
            FutureSystemChartCtrl.Series["최저"].ToolTip = "#VALX : #VAL";
            FutureSystemChartCtrl.Series["상위"].ToolTip = "#VALX : #VAL";
            FutureSystemChartCtrl.Series["하위"].ToolTip = "#VALX : #VAL";
            FutureSystemChartCtrl.Series["기상위"].ToolTip = "#VALX : #VAL";
            FutureSystemChartCtrl.Series["기하위"].ToolTip = "#VALX : #VAL";
            FutureSystemChartCtrl.Series["Forecasting"].ToolTip = "#VALX : #VAL";
            FutureSystemChartCtrl.Series["현재평균파"].ToolTip = "#VALX : #VAL";
            FutureSystemChartCtrl.Series["신호평균파"].ToolTip = "#VALX : #VAL";

            FutureSystemChartCtrl.Series["최고"].Enabled = false;
            FutureSystemChartCtrl.Series["최저"].Enabled = false;
            FutureSystemChartCtrl.Series["상위"].Enabled = false;
            FutureSystemChartCtrl.Series["하위"].Enabled = false;

            //cbCurWaveReg.Checked = true;
            //cbSigWaveReg.Checked = true;
            cbShowWave.Checked = true;
            cbShowPrice.Checked = false;
            cbShowSignal.Checked = true;
            //FutureSystemChartCtrl.EnableZoomAndPanControls(ChartCursorSelected, ChartCursorMoved);
            cbZoom.Checked = false;
            //cbForecasting.Checked = false;
            cbPrice.Checked = true;
            cbHigh.Checked = false;
            cbLow.Checked = false;
            Series series = FutureSystemChartCtrl.Series["지수"];
            if (series == null)
                return;
            if (cbPrice.Checked)
            {
                series.Enabled = true;
            }
            else
            {
                series.Enabled = false;
            }

            series = FutureSystemChartCtrl.Series["최고"];
            if (series == null)
                return;
            

            series = FutureSystemChartCtrl.Series["최저"];
            if (series == null)
                return;
            

            series = FutureSystemChartCtrl.Series["상위"];
            if (series == null)
                return;
            if (cbHigh.Checked)
            {
                series.Enabled = true;
            }
            else
            {
                series.Enabled = false;
            }

            series = FutureSystemChartCtrl.Series["하위"];
            if (series == null)
                return;
            if (cbLow.Checked)
            {
                series.Enabled = true;
            }
            else
            {
                series.Enabled = false;
            }

        }

        private void ChartCursorSelected(double x, double y)
        {
            int curIndex = (int)x;
            int pointCount = FutureSystemChartCtrl.Series["지수"].Points.Count;
            if (curIndex <= 0 || curIndex >= pointCount)
                return;
            string curTime = FutureSystemChartCtrl.Series["지수"].Points[curIndex].AxisLabel;
            string minText = curTime.Substring(curTime.Length - 2, 2);
            string hourText = curTime.Substring(0, curTime.Length - 2);

            txtChartSelect.Text = "선택된 값 : " + hourText + "시 " + minText + "분 , " + y.ToString("F2");
        }
        private void ChartCursorMoved(double x, double y)
        {
            int curIndex = (int)x;
            int pointCount = FutureSystemChartCtrl.Series["지수"].Points.Count;
            if (curIndex <= 0 || curIndex >= pointCount)
                return;
            string curTime = FutureSystemChartCtrl.Series["지수"].Points[curIndex].AxisLabel;
            string minText = curTime.Substring(curTime.Length - 2, 2);
            string hourText = curTime.Substring(0, curTime.Length - 2);

            txtChartValue.Text = "   마우스위치 : " + hourText + "시 " + minText + "분 , " + y.ToString("F2");
        }

        // 여기서 차트를 갱신해 준다.
        private void OnTimerTick(object sender, EventArgs e)
        {
            // 차트에 데이터를 대응시켜 준다.
            //SetOptChartData();
            MakeFutDDEVal();
            SetChartData();
            // 파동을 그려준다.
            if (m_WaveManager != null)
            {
                // 파동을 만들어 놓는다.
                m_WaveManager.MakeWaveListFromFutOptChart();
                PriceWaveList curWaveList = m_WaveManager.ArragedWaveList;
                SetWaveOnChart(curWaveList);
            }

            ShowCurValue();
            string valueText = "";
            if (GlobalVar.ProgressVal > 0)
            {
                signalProgressBar.StartColor = Color.Red;
                signalProgressBar.EndColor = Color.Red;
                valueText = "매수 : ";
            }
            else
            {
                signalProgressBar.StartColor = Color.Blue;
                signalProgressBar.EndColor = Color.Blue;
                valueText = "매도 : ";
            }

            signalProgressBar.Value = Math.Abs(GlobalVar.ProgressVal);
            valueText += signalProgressBar.Value.ToString();
            valueText += "%";
            signalProgressBar.ValueText = valueText;
            SaveChartImage();
            ShowProfit();
        }

        private void SetRegWaveOnChart(EasyTrader.Signal.ForecastingInfo a_CurInfo, EasyTrader.Signal.ForecastingInfo a_SigInfo)
        {
            if (a_CurInfo == null || a_SigInfo == null)
                return;

            // 먼저 이전에 모든 점들을 없애 준다.
            FutureSystemChartCtrl.Series["현재평균파"].Points.Clear();
            FutureSystemChartCtrl.Series["신호평균파"].Points.Clear();

            FutureSystemChartCtrl.Series["현재평균파"].Points.AddXY(a_CurInfo.StartX, a_CurInfo.StartY);
            FutureSystemChartCtrl.Series["현재평균파"].Points.AddXY(a_CurInfo.EndX, a_CurInfo.EndY);

            FutureSystemChartCtrl.Series["신호평균파"].Points.AddXY(a_SigInfo.StartX, a_SigInfo.StartY);
            FutureSystemChartCtrl.Series["신호평균파"].Points.AddXY(a_SigInfo.EndX, a_SigInfo.EndY);
        }

        private void ShowProfit()
        {
            if (m_TotalSignalManager == null || m_CPDataSet == null)
                return;
            int dayIndex = GlobalVar.DayIndex();
            EasyTrader.DataSet.FutOptChartTable dataTable = m_CPDataSet.GetFutOptChartTable();
            int rowCount = dataTable.GetRowCount();
            if (rowCount == 0)
                return;
            if (rowCount - 1 < dayIndex)
                dayIndex = rowCount - 1;

            DataRow row = dataTable.Rows[dayIndex];
            double closeValue = Convert.ToDouble(row["종가"]);

            double curProfit = m_TotalSignalManager.CalcCurProfit(m_TotalSignalManager.FindSignalListBySysType(m_SysType), closeValue);
            double totalProfit = m_TotalSignalManager.CalcTotalProfit(m_TotalSignalManager.FindSignalListBySysType(m_SysType), closeValue);

            txtCurProfit.Text = "현재수익 : " + curProfit.ToString("F2") + " 만원";
            txtTotalProfit.Text = "전체수익 : " + totalProfit.ToString("F2") + " 만원";
        }

        private void DrawSignal(PriceSignalList a_SignalList, ChartPaintEventArgs a_EventArg)
        {
            if (a_SignalList == null)
                return;

            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;
                if (area.Name == "Price")
                {
                    double highXValue = 0;
                    double highYValue = 0;

                    Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                    Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                    FontStyle.Regular);

                    System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                    // Set the TextRenderingHint property.
                    graphics.TextRenderingHint =
                        System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                    string valueText = "";
                    //List<TrendWave> waveList = a_WaveList.WaveList;
                    for (int i = 0; i < a_SignalList.Count; i++)
                    {
                        EasyTrader.Signal.PriceSignal curSignal = a_SignalList[i];

                        highXValue = curSignal.X;
                        highYValue = curSignal.Y;

                        string curValue = String.Format("{0:F2}", curSignal.Y);

                        // Convert X and Y values to screen position
                        float pixelYMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.Y, highYValue);
                        float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.X, highXValue);
                        float pixelYMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.Y, highYValue);
                        float pixelXMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.X, highXValue);

                        // Specify width of triangle
                        float width = 1;

                        // Set Maximum points
                        PointF[] points = new PointF[3];
                        points[0].X = pixelXMax - width;
                        points[0].Y = pixelYMax - width - 2;
                        points[1].X = pixelXMax + width;
                        points[1].Y = pixelYMax - width - 2;
                        points[2].X = pixelXMax;
                        points[2].Y = pixelYMax - 1;

                        // Convert relative coordinates to absolute coordinates.
                        points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                        points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                        points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                        // 고점 변곡점 타입일 때. 하향을 향하므로 매도 사인을 낸다.
                        if (curSignal.Type == GlobalVar.SignalSell)
                        {
                            // Draw Maximum trangle
                            graphics.FillPolygon(new SolidBrush(Color.Blue), points);
                            string curTime = curSignal.Time.ToString();
                            if (curTime != "0")
                            {
                                string minText = curTime.Substring(curTime.Length - 2, 2);
                                string hourText = curTime.Substring(0, curTime.Length - 2);
                                curTime = hourText + ":" + minText;
                            }
                            valueText = "매도[";
                            if (curSignal.SignalState == GlobalVar.SignalStateFirst)
                            {
                                valueText += "초입";
                            }
                            else if (curSignal.SignalState == GlobalVar.SignalStateTrans)
                            {
                                valueText += "전환";
                            }
                            else if (curSignal.SignalState == GlobalVar.SignalStateOver)
                            {
                                valueText += "돌파";
                            }
                            else if (curSignal.SignalState == GlobalVar.SignalStateLiquid)
                            {
                                valueText += "청산";
                            }
                            else if (curSignal.SignalState == GlobalVar.SignalStateCorrect)
                            {
                                valueText += "수정";
                            }
                            else
                            {
                                valueText += "없음";
                            }
                            valueText += "]";
                            valueText += "(" + curTime + " , " + curValue + ")";
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Blue, points[2].X, points[2].Y - width);
                        }
                        if (curSignal.Type == GlobalVar.SignalExitBuy)
                        {
                            // Draw Maximum trangle
                            graphics.FillPolygon(new SolidBrush(Color.Green), points);
                            string curTime = curSignal.Time.ToString();
                            if (curTime != "0")
                            {
                                string minText = curTime.Substring(curTime.Length - 2, 2);
                                string hourText = curTime.Substring(0, curTime.Length - 2);
                                curTime = hourText + ":" + minText;
                            }
                            valueText = "[매수청산]";
                            valueText += "(" + curTime + " , " + curValue + ")";
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Blue, points[2].X, points[2].Y - width);
                        }

                        if (curSignal.Type == GlobalVar.SignalBuyPartialLiquid)
                        {
                            // Draw Maximum trangle
                            graphics.FillPolygon(new SolidBrush(Color.Magenta), points);
                            string curTime = curSignal.Time.ToString();
                            if (curTime != "0")
                            {
                                string minText = curTime.Substring(curTime.Length - 2, 2);
                                string hourText = curTime.Substring(0, curTime.Length - 2);
                                curTime = hourText + ":" + minText;
                            }
                            valueText = "[매수부분청산]";
                            valueText += "(" + curTime + " , " + curValue + ")";
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Red, points[2].X, points[2].Y - width);
                        }

                        // Set Minimum points
                        points = new PointF[3];
                        points[0].X = pixelXMin - width;
                        points[0].Y = pixelYMin + width + 2;
                        points[1].X = pixelXMin + width;
                        points[1].Y = pixelYMin + width + 2;
                        points[2].X = pixelXMin;
                        points[2].Y = pixelYMin + 1;

                        // Convert relative coordinates to absolute coordinates.
                        points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                        points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                        points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                        // 고점 변곡점 타입일 때. 상향을 향하므로 매수 사인을 낸다.
                        if (curSignal.Type == GlobalVar.SignalBuy)
                        {
                            // Draw Minimum triangle
                            graphics.FillPolygon(new SolidBrush(Color.Red), points);
                            string curTime = curSignal.Time.ToString();
                            if (curTime != "0")
                            {
                                string minText = curTime.Substring(curTime.Length - 2, 2);
                                string hourText = curTime.Substring(0, curTime.Length - 2);
                                curTime = hourText + ":" + minText;
                            }
                            valueText = "매수[";
                            if (curSignal.SignalState == GlobalVar.SignalStateFirst)
                            {
                                valueText += "초입";
                            }
                            else if (curSignal.SignalState == GlobalVar.SignalStateTrans)
                            {
                                valueText += "전환";
                            }
                            else if (curSignal.SignalState == GlobalVar.SignalStateOver)
                            {
                                valueText += "돌파";
                            }
                            else if (curSignal.SignalState == GlobalVar.SignalStateLiquid)
                            {
                                valueText += "청산";
                            }
                            else if (curSignal.SignalState == GlobalVar.SignalStateCorrect)
                            {
                                valueText += "수정";
                            }
                            else
                            {
                                valueText += "없음";
                            }
                            valueText += "]";
                            valueText += "(" + curTime + " , " + curValue + ")";
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Red, points[2].X, points[2].Y - 15);
                        }
                        if (curSignal.Type == GlobalVar.SignalExitSell)
                        {
                            // Draw Minimum triangle
                            graphics.FillPolygon(new SolidBrush(Color.Green), points);
                            string curTime = curSignal.Time.ToString();
                            if (curTime != "0")
                            {
                                string minText = curTime.Substring(curTime.Length - 2, 2);
                                string hourText = curTime.Substring(0, curTime.Length - 2);
                                curTime = hourText + ":" + minText;
                            }
                            valueText = "[매도청산]";
                            valueText += "(" + curTime + " , " + curValue + ")";
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Red, points[2].X, points[2].Y - 15);
                        }

                        if (curSignal.Type == GlobalVar.SignalSellPartialLiquid)
                        {
                            // Draw Minimum triangle
                            graphics.FillPolygon(new SolidBrush(Color.Cyan), points);
                            string curTime = curSignal.Time.ToString();
                            if (curTime != "0")
                            {
                                string minText = curTime.Substring(curTime.Length - 2, 2);
                                string hourText = curTime.Substring(0, curTime.Length - 2);
                                curTime = hourText + ":" + minText;
                            }
                            valueText = "[매도부분청산]";
                            valueText += "(" + curTime + " , " + curValue + ")";
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Blue, points[2].X, points[2].Y - 15);
                        }
                    }
                }
            }
        }



        private void DrawOpVal(ChartPaintEventArgs a_EventArg)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;
                if (area.Name == "Price")
                {
                    double highXValue = 0;
                    double highYValue = 0;

                    Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                    Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                    FontStyle.Bold);

                    System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                    // Set the TextRenderingHint property.
                    graphics.TextRenderingHint =
                        System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                    string valueText = "";
                    if (GlobalVar.OPNVAL.BreakCode != "")
                    {
                        string sideCode = GlobalVar.OPNVAL.BreakCode.Substring(0, 1);
                        string priceCode = GlobalVar.OPNVAL.BreakCode.Substring(GlobalVar.OPNVAL.BreakCode.Length - 3, 3);
                        if (sideCode == "2")
                        {
                            valueText += "콜 : " + priceCode + "\n";
                        }
                        else
                        {
                            valueText += "풋 : " + priceCode + "\n";
                        }
                    }
                    valueText +=  "가격 : " + GlobalVar.OPNVAL.Val.ToString("F2") + "\n";
                    valueText += "현재가 : " + GlobalVar.OPNVAL.CurVal.ToString("F2") + "\n";
                    valueText += "차이 : " + GlobalVar.OPNVAL.DeltaY.ToString("F2") + "\n";
                    if (GlobalVar.OPNVAL.Type == 0)
                    {
                        valueText += "종류 : " + "월저가";
                    }
                    else if (GlobalVar.OPNVAL.Type == 1)
                    {
                        valueText += "종류 : " + "마디가";
                    }
                    else if (GlobalVar.OPNVAL.Type == 2)
                    {
                        valueText += "종류 : " + "기준가";
                    }
                    else if (GlobalVar.OPNVAL.Type == 3)
                    {
                        valueText += "종류 : " + "목표가";
                    }
                    else if (GlobalVar.OPNVAL.Type == 4)
                    {
                        valueText += "종류 : " + "월고가";
                    }

                    highXValue = GlobalVar.OPNVAL.Index;
                    highYValue = GlobalVar.OPNVAL.Y;
                    
                    // Convert X and Y values to screen position
                    float pixelYMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.Y, highYValue);
                    float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.X, highXValue);

                    // Specify width of triangle
                    float width = 1;

                    // Set Maximum points
                    PointF[] points = new PointF[3];
                    points[0].X = pixelXMax;
                    points[0].Y = pixelYMax;
                    points[1].X = pixelXMax - width;
                    points[1].Y = pixelYMax - 2;
                    points[2].X = pixelXMax - width;
                    points[2].Y = pixelYMax + 2;

                    // Convert relative coordinates to absolute coordinates.
                    points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                    points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                    points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                    DateTime date = DateTime.Now;
                    if (Math.Abs(GlobalVar.OPNVAL.DeltaY) < 0.2)
                    {
                        int mod = date.Second % 2;
                        if (mod == 0)
                        {
                            graphics.FillPolygon(new SolidBrush(Color.Blue), points);
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Blue, points[0].X - 100, points[0].Y - 35);
                        }
                        else
                        {
                            graphics.FillPolygon(new SolidBrush(Color.Red), points);
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Red, points[0].X - 100, points[0].Y - 35);
                        }


                    }
                    else
                    {
                        if (GlobalVar.OPNVAL.DeltaY > 0)
                        {
                            graphics.FillPolygon(new SolidBrush(Color.Red), points);
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Red, points[0].X - 100, points[0].Y - 35);
                        }
                        else
                        {
                            graphics.FillPolygon(new SolidBrush(Color.Blue), points);
                            // Draw the string.
                            graphics.DrawString(valueText, myFont,
                                Brushes.Blue, points[0].X - 100, points[0].Y - 35);
                        }
                    }
                }
            }
        }



        private void SetForecastingYOnChart(EasyTrader.Signal.ForecastingInfo a_ForeInfo)
        {
            if (m_WaveSignalManager == null || a_ForeInfo == null)
                return;

            /*
            // 먼저 이전에 모든 점들을 없애 준다.
            FutureSystemChartCtrl.Series["예상가"].Points.Clear();
            for (int i = 0; i < m_WaveSignalManager.ForePriceList.Count; i++)
            {
                EasyTrader.Wave.PricePoint point = m_WaveSignalManager.ForePriceList[i];
                FutureSystemChartCtrl.Series["예상가"].Points.AddXY(point.X, point.Y);
            }*/

            //int result = m_WaveSignalManager.GetForecastingInfo(m_ForecastInfo, "종가", GlobalVar.RegressionType, GlobalVar.PriceReferenceRange);
            if (FutureSystemChartCtrl.Series["Forecasting"] != null)
            {
                FutureSystemChartCtrl.Series["Forecasting"].Points.Clear();
                FutureSystemChartCtrl.Series["Forecasting"].Points.AddXY(a_ForeInfo.StartX, a_ForeInfo.StartY);
                FutureSystemChartCtrl.Series["Forecasting"].Points.AddXY(a_ForeInfo.EndX, a_ForeInfo.EndY);
            }
        }
        private void ShowCurValue()
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_CPDataSet == null || GlobalVar.FutOptChartDataDownloaded == false)
                return;

            EasyTrader.DataSet.FutOptChartTable dataTable = m_CPDataSet.GetFutOptChartTable();
            int rowCount = dataTable.GetRowCount();
            if (rowCount == 0)
                return;

            DataRow row = dataTable.Rows[rowCount - 1];
            double closeValue = Convert.ToDouble(row["종가"]);
            string curTime = row["시각"].ToString();
            double stdVal = m_CPDataSet.FindTodayBase();
            if (curTime != "0")
            {
                string minText = curTime.Substring(curTime.Length - 2, 2);
                string hourText = curTime.Substring(0, curTime.Length - 2);

                txtCurTime.Text = "현재시간 " + hourText + " : " + minText;
                txtCurPrice.Text = "현재가격 " + closeValue.ToString("F2") + " , 기준가 : " + stdVal.ToString("F2");
                //txtPriceAngle.Text = "현재 값각도 : " + GlobalVar.PriceAngle.ToString("F2");
                //txtReverseRatio.Text = "반발계수 : " + GlobalVar.ReverseRatio.ToString("F2");
            }

            if (m_TotalSignalManager != null)
            {
                //txtCurWaveRegHeight.Text = "현재평균파높이 : " + m_TotalSignalManager.CurWaveRegression.Height().ToString("F2");
                //txtSigWaveRegHeight.Text = "현재신호파높이 : " + m_TotalSignalManager.LastSignalRegression.Height().ToString("F2");
                //if (m_TotalSignalManager.CurWave != null)
                //    txtCurWaveHeight.Text = "현재파동높이 : " + m_TotalSignalManager.CurWave.Height().ToString("F2");
                //double dailyGap = m_TotalSignalManager.GetTodayDailyGap();
                //if (dailyGap != 0.0)
                //{
                //    txtPriceDailyGap.Text = "일간 지수차이 : " + dailyGap.ToString("F2");
                //}
            }
        }

        private double m_Max = -999.0;
        private double m_Min = 999.0;

        private int m_ShowType = 2; // 0 : 모두 , 1 : 선물만, 2 : 옵션만, 3 : 콜만, 4 : 풋만

        // 차트 데이터 목록에서 중심으로 사용하는 인덱스이다.
        // 이 중심 인덱스를 중심으로 위아래 행사가의 개수가 차트에 나타 난다.
        private int m_CenterIndex = 1;
        public int CenterIndex
        {
            get { return m_CenterIndex; }
            set { m_CenterIndex = value; }
        }

        // 차트 중심 인덱스를 중심으로 행사가를 위아래로 몇개씩 포함시킬 것인지 정한다.
        // 0일 경우는 중심 행사가만을 포함하게 된다.
        private int m_IndexRange = 0;
        public int IndexRange
        {
            get { return m_IndexRange; }
            set { m_IndexRange = value; }
        }

        private bool m_DataFilled = false;

        private BarTableList m_ChartTableList = new BarTableList();
        private DDEDataList m_DDEValList = new DDEDataList();
        private DDEDataList m_FutDDEValList = new DDEDataList();
        private SimpleDataList m_CrossValList = new SimpleDataList();

        private bool m_EnableBase = true;
        private bool m_EnableMonthHigh = true;
        private bool m_EnableMonthLow = true;
        //private bool m_EnablePreDayHigh = true;
        //private bool m_EnablePreDayLow = true;
        //private bool m_EnableOpConstPrice = false;
        private bool m_EnableJoint = true;
        private bool m_EnableTarget = true;
        private bool m_EnableCross = false;

        private void MakeDataTableList()
        {
            m_ChartTableList.Clear();
            int listCount = m_CPDataSet.OptChartTableList.Count;
            // 여기서 중심 인덱스를 찾아서 설정해 준다.

            int startIndex = m_CenterIndex - m_IndexRange;
            if (startIndex < 0)
                startIndex = 0;
            int endIndex = m_CenterIndex + m_IndexRange;
            if (endIndex > listCount - 1)
                endIndex = listCount - 1;
            // 콜 테이블 추가
            for (int i = startIndex; i <= endIndex; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_CPDataSet.OptChartTableList[i];
                m_ChartTableList.Add(table);
            }

            int index = m_CenterIndex + (int)(listCount / 2.0);
            startIndex = index - m_IndexRange;
            if (startIndex < 0)
                startIndex = 0;
            endIndex = index + m_IndexRange;
            if (endIndex > listCount - 1)
                endIndex = listCount - 1;
            // 풋 테이블 추가
            for (int i = startIndex; i <= endIndex; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_CPDataSet.OptChartTableList[i];
                m_ChartTableList.Add(table);
            }
        }

        private void DrawOpDDEPrice(ChartPaintEventArgs a_EventArg)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;

                for (int i = 0; i < m_DDEValList.Count; i++)
                {
                    EasyTrader.Option.DDEData curDDE = m_DDEValList[i];
                    if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 3)
                    {
                        DrawOpDDEVal(a_EventArg, 0, Convert.ToDouble(curDDE.DataItem.PutBase), curDDE.CallCode.ToString());
                        DrawOpDDEVal(a_EventArg, 1, Convert.ToDouble(curDDE.DataItem.PutMLow), curDDE.CallCode.ToString());
                        DrawOpDDEVal(a_EventArg, 2, Convert.ToDouble(curDDE.DataItem.PutMHigh), curDDE.CallCode.ToString());
                    }
                    if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 4)
                    {
                        DrawOpDDEVal(a_EventArg, 0, Convert.ToDouble(curDDE.DataItem.CallBase), curDDE.PutCode.ToString());
                        DrawOpDDEVal(a_EventArg, 1, Convert.ToDouble(curDDE.DataItem.CallMLow), curDDE.PutCode.ToString());
                        DrawOpDDEVal(a_EventArg, 2, Convert.ToDouble(curDDE.DataItem.CallMHigh), curDDE.PutCode.ToString());
                    }
                }

            }

            //FutOptChartCtrl.Invalidate(false);
        }
        private void DrawFutDDEPrice(ChartPaintEventArgs a_EventArg)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;

                for (int i = 0; i < m_FutDDEValList.Count; i++)
                {
                    EasyTrader.Option.DDEData curDDE = m_FutDDEValList[i];
                    if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 3)
                    {
                        DrawFutDDEVal(a_EventArg, 0, curDDE.FutCall[0], curDDE.CallCode.ToString());
                        DrawFutDDEVal(a_EventArg, 1, curDDE.FutCall[1], curDDE.CallCode.ToString());
                        DrawFutDDEVal(a_EventArg, 2, curDDE.FutCall[2], curDDE.CallCode.ToString());
                        DrawFutDDEVal(a_EventArg, 3, curDDE.FutCall[3], curDDE.CallCode.ToString());
                        DrawFutDDEVal(a_EventArg, 4, curDDE.FutCall[4], curDDE.CallCode.ToString());
                    }
                    if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 4)
                    {
                        DrawFutDDEVal(a_EventArg, 0, curDDE.FutPut[0], curDDE.PutCode.ToString());
                        DrawFutDDEVal(a_EventArg, 1, curDDE.FutPut[1], curDDE.PutCode.ToString());
                        DrawFutDDEVal(a_EventArg, 2, curDDE.FutPut[2], curDDE.PutCode.ToString());
                        DrawFutDDEVal(a_EventArg, 3, curDDE.FutPut[3], curDDE.PutCode.ToString());
                        DrawFutDDEVal(a_EventArg, 4, curDDE.FutPut[4], curDDE.PutCode.ToString());
                    }
                }

            }

            //FutOptChartCtrl.Invalidate(false);
        }

        private void DrawCrossPrice(ChartPaintEventArgs a_EventArg)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;

                for (int i = 0; i < m_CrossValList.Count; i++)
                {
                    EasyTrader.DataSet.SimpleData curDDE = m_CrossValList[i];
                    // 콜
                    if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 3)
                    {
                        DrawCrossVal(a_EventArg, curDDE.PutType, curDDE.PutVal, curDDE.CallCode, curDDE.CenterVal);
                    }
                    // 풋
                    if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 4)
                    {
                        DrawCrossVal(a_EventArg, curDDE.CallType, curDDE.CallVal, curDDE.PutCode, curDDE.CenterVal);
                    }
                }

            }

        }

        private void DrawCrossVal(ChartPaintEventArgs a_EventArg, int a_Type, double a_Val, string a_Code, string a_CenterVal)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;

                double xMin = 0.0;
                double xMax = 0.0;
                double YValue = 0.0;
                double YMin = 0.0;
                double YMax = 0.0;
                string sideCode = a_Code.Substring(0, 1);
                string priceCode = a_Code.Substring(a_Code.Length - 3, 3);

                string valueText = "";
                if (sideCode == "2")
                    valueText += "콜" + priceCode + " : ";
                else
                    valueText += "풋" + priceCode + " : ";

                if (a_Type == 0)
                {
                    if (priceCode == a_CenterVal)
                        valueText += "상대중심마디가";
                    else
                        valueText += "상대마디가";
                }
                else if (a_Type == 1)
                {
                    if (priceCode == a_CenterVal)
                        valueText += "상대중심목표가";
                    else
                        valueText += "상대목표가";
                }


                if (a_Type == 0 && m_EnableJoint == false)
                    return;
                if (a_Type == 1 && m_EnableTarget == false)
                    return;


                Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                FontStyle.Regular);

                System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                // Set the TextRenderingHint property.
                graphics.TextRenderingHint =
                    System.Drawing.Text.TextRenderingHint.AntiAlias;


                xMin = area.AxisX.Minimum;
                xMax = area.AxisX.Maximum;
                YMin = area.AxisY2.Minimum;
                YMax = area.AxisY2.Maximum;
                YValue = a_Val;

                if (YValue > YMax || YValue < YMin)
                    return;

                string curValue = String.Format("{0:F2}", YValue);

                valueText += " : " + curValue;

                // Convert X and Y values to screen position
                float pixelY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y2, YValue);
                float pixelMaxY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y2, area.AxisY2.Maximum);
                float pixelXMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMin);
                float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMax);

                // Set Maximum points
                PointF[] points = new PointF[3];
                points[0].X = pixelXMin;
                points[0].Y = pixelY;

                points[1].X = pixelXMax;
                points[1].Y = pixelY;

                points[2].X = pixelXMin;
                points[2].Y = pixelMaxY;


                // Convert relative coordinates to absolute coordinates.
                points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                if (sideCode == "2")
                {
                    graphics.DrawLine(new Pen(Color.Red, 1), points[0], points[1]);
                    graphics.DrawString(valueText, myFont, Brushes.Red, points[0].X + 150, points[0].Y);
                }
                else
                {
                    graphics.DrawLine(new Pen(Color.Blue, 1), points[0], points[1]);
                    graphics.DrawString(valueText, myFont, Brushes.Blue, points[0].X + 150, points[0].Y);
                }

            }
        }

        // ddde val type : 0 : 기준가, 1 : 월저가, 2 : 월고가, 3 : 마디가, 4 : 목표가, 5 : 교차가
        private void DrawOpDDEVal(ChartPaintEventArgs a_EventArg, int a_Type, double a_Val, string a_Code)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;

                double xMin = 0.0;
                double xMax = 0.0;
                double YValue = 0.0;
                double YMin = 0.0;
                double YMax = 0.0;
                string sideCode = a_Code.Substring(0, 1);
                string priceCode = a_Code.Substring(a_Code.Length - 3, 3);

                string valueText = "";
                if (sideCode == "2")
                    valueText += "콜" + priceCode + " : ";
                else
                    valueText += "풋" + priceCode + " : ";

                if (a_Type == 0)
                    valueText += "상대기준가";
                else if (a_Type == 1)
                    valueText += "상대월저가";
                else if (a_Type == 2)
                    valueText += "상대월고가";
                else if (a_Type == 3)
                    valueText += "상대마디가";
                else if (a_Type == 4)
                    valueText += "상대목표가";
                else if (a_Type == 5)
                    valueText += "교차가";

                if (a_Type == 0 && m_EnableBase == false)
                    return;
                if (a_Type == 1 && m_EnableMonthLow == false)
                    return;
                if (a_Type == 2 && m_EnableMonthHigh == false)
                    return;
                if (a_Type == 3 && m_EnableJoint == false)
                    return;
                if (a_Type == 4 && m_EnableTarget == false)
                    return;
                if (a_Type == 5 && m_EnableCross == false)
                    return;

                Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                FontStyle.Regular);

                System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                // Set the TextRenderingHint property.
                graphics.TextRenderingHint =
                    System.Drawing.Text.TextRenderingHint.AntiAlias;


                xMin = area.AxisX.Minimum;
                xMax = area.AxisX.Maximum;
                YMin = area.AxisY2.Minimum;
                YMax = area.AxisY2.Maximum;
                YValue = a_Val;

                /*
                if (YValue > YMax || YValue < YMin)
                    return;
                if (YValue == double.NaN)
                    return;
                 */

                string curValue = String.Format("{0:F2}", YValue);

                valueText += " : " + curValue;

                // Convert X and Y values to screen position
                float pixelY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y2, YValue);
                float pixelMaxY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y2, area.AxisY2.Maximum);
                float pixelXMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMin);
                float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMax);


                // Set Maximum points
                PointF[] points = new PointF[3];
                points[0].X = pixelXMin;
                points[0].Y = pixelY;

                points[1].X = pixelXMax;
                points[1].Y = pixelY;

                points[2].X = pixelXMin;
                points[2].Y = pixelMaxY;


                // Convert relative coordinates to absolute coordinates.
                points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                if (sideCode == "2")
                {
                    graphics.DrawLine(new Pen(Color.Red, 1), points[0], points[1]);
                    graphics.DrawString(valueText, myFont, Brushes.Red, points[0].X, points[0].Y);
                }
                else
                {
                    graphics.DrawLine(new Pen(Color.Blue, 1), points[0], points[1]);
                    graphics.DrawString(valueText, myFont, Brushes.Blue, points[0].X, points[0].Y);
                }

            }
        }


        // ddde val type : 0 : 기준가, 1 : 월저가, 2 : 월고가, 3 : 마디가, 4 : 목표가, 5 : 교차가
        private void DrawFutDDEVal(ChartPaintEventArgs a_EventArg, int a_Type, double a_Val, string a_Code)
        {
            double fmin = 0.0, fmax = 0.0;
            EasyTrader.DataSet.FutOptChartTable dataTable = m_CPDataSet.GetFutOptChartTable();
            GlobalVar.FindMinMax(dataTable, 0, GlobalVar.DayIndex(), ref fmin, ref fmax);
            if (a_Val == 0.0 || a_Val < fmin - 1.0 || a_Val > fmax + 1.0)
                return;

            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;

                double xMin = 0.0;
                double xMax = 0.0;
                double YValue = 0.0;
                double YMin = 0.0;
                double YMax = 0.0;
                string sideCode = a_Code.Substring(0, 1);
                string priceCode = a_Code.Substring(a_Code.Length - 3, 3);

                string valueText = "";
                if (sideCode == "2")
                    valueText += "콜" + priceCode + " : ";
                else
                    valueText += "풋" + priceCode + " : ";

                if (a_Type == 0)
                    valueText += "상대월저가";
                else if (a_Type == 1)
                    valueText += "상대마디가";
                else if (a_Type == 2)
                    valueText += "상대기준가";
                else if (a_Type == 3)
                    valueText += "상대목표가";
                else if (a_Type == 4)
                    valueText += "상대월고가";
                else if (a_Type == 5)
                    valueText += "교차가";

                if (a_Type == 0 && m_EnableBase == false)
                    return;
                if (a_Type == 1 && m_EnableMonthLow == false)
                    return;
                if (a_Type == 2 && m_EnableMonthHigh == false)
                    return;
                if (a_Type == 3 && m_EnableJoint == false)
                    return;
                if (a_Type == 4 && m_EnableTarget == false)
                    return;
                if (a_Type == 5 && m_EnableCross == false)
                    return;

                Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                FontStyle.Regular);

                System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                // Set the TextRenderingHint property.
                graphics.TextRenderingHint =
                    System.Drawing.Text.TextRenderingHint.AntiAlias;


                xMin = area.AxisX.Minimum;
                xMax = area.AxisX.Maximum;
                YMin = area.AxisY.Minimum;
                YMax = area.AxisY.Maximum;
                YValue = a_Val;

                /*
                if (YValue > YMax || YValue < YMin)
                    return;
                if (YValue == double.NaN)
                    return;
                 */

                string curValue = String.Format("{0:F2}", YValue);

                valueText += " : " + curValue;

                // Convert X and Y values to screen position
                float pixelY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y, YValue);
                float pixelMaxY = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.Y, area.AxisY.Maximum);
                float pixelXMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMin);
                float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis(area.Name, AxisName.X, xMax);


                // Set Maximum points
                PointF[] points = new PointF[3];
                points[0].X = pixelXMin;
                points[0].Y = pixelY;

                points[1].X = pixelXMax;
                points[1].Y = pixelY;

                points[2].X = pixelXMin;
                points[2].Y = pixelMaxY;


                // Convert relative coordinates to absolute coordinates.
                points[0] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[0]);
                points[1] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[1]);
                points[2] = a_EventArg.ChartGraphics.GetAbsolutePoint(points[2]);

                if (sideCode == "2")
                {
                    graphics.DrawLine(new Pen(Color.Red, 1), points[0], points[1]);
                    graphics.DrawString(valueText, myFont, Brushes.Red, points[0].X, points[0].Y);
                }
                else
                {
                    graphics.DrawLine(new Pen(Color.Blue, 1), points[0], points[1]);
                    graphics.DrawString(valueText, myFont, Brushes.Blue, points[0].X, points[0].Y);
                }

            }
        }

        private int m_Mode = GlobalVar.OpCallMode;

        private void MakeFutDDEVal()
        {
            if (m_CPDataSet == null)
                return;
            if (m_CPDataSet.DownLoader.AllOptChartDataDownloaded == false ||
                m_CPDataSet.DownLoader.ATMChanged == false)
                return;

            m_FutDDEValList.Clear();
            double omin = 0.0, omax = 0.0;
            double fmin = 0.0, fmax = 0.0;
            EasyTrader.DataSet.FutOptChartTable dataTable = m_CPDataSet.GetFutOptChartTable();

            GlobalVar.FindMinMax(dataTable, 0, GlobalVar.DayIndex(), ref fmin, ref fmax);
            for (int i = 0; i < m_CPDataSet.OptChartTableList.Count; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_CPDataSet.OptChartTableList[i];
                string sideCode = table.TableName.Substring(0, 1);
                GlobalVar.FindMinMax(table, 0, GlobalVar.DayIndex(), ref omin, ref omax);
                
                EasyTrader.Option.DDEData curDDE = FindFutDDEVal(table.TableName);
                if (curDDE == null)
                {
                    curDDE = m_CPDataSet.FindDDEData(m_CPDataSet.DownLoader.CurDay, table.TableName);
                }
                if (curDDE != null)
                {
                    
                    m_FutDDEValList.Add(curDDE);
                    if (sideCode == "2")
                    {
                        if (GlobalVar.DayIndex() < 2)
                        {
                            omin = Convert.ToDouble(curDDE.DataItem.CallPreLow);
                            omax = Convert.ToDouble(curDDE.DataItem.CallPreHigh);
                        }
                        double deltaOp = Math.Abs(omax - omin);
                        double opVal = Convert.ToDouble(curDDE.DataItem.PutMLow);
                        double deltaDDE = Math.Abs(opVal - omin);
                        double deltaFut = Math.Abs(fmax - fmin);
                        double FutNewVal = (deltaDDE / deltaOp) * deltaFut;
                        if (deltaOp == 0.0 || deltaFut == 0.0)
                            continue;

                        if (opVal > omin)
                        {
                            curDDE.FutCall[0] = fmin + FutNewVal;
                        }
                        else
                        {
                            curDDE.FutCall[0] = fmin - FutNewVal;
                        }

                        opVal = curDDE.PutJoint;
                        deltaDDE = Math.Abs(opVal - omin);
                        FutNewVal = (deltaDDE / deltaOp) * deltaFut;
                        if (opVal > omin)
                        {
                            curDDE.FutCall[1] = fmin + FutNewVal;
                        }
                        else
                        {
                            curDDE.FutCall[1] = fmin - FutNewVal;
                        }

                        opVal = Convert.ToDouble(curDDE.DataItem.PutBase);
                        deltaDDE = Math.Abs(opVal - omin);
                        FutNewVal = (deltaDDE / deltaOp) * deltaFut;
                        if (opVal > omin)
                        {
                            curDDE.FutCall[2] = fmin + FutNewVal;
                        }
                        else
                        {
                            curDDE.FutCall[2] = fmin - FutNewVal;
                        }

                        opVal = curDDE.PutTarget;
                        deltaDDE = Math.Abs(opVal - omin);
                        FutNewVal = (deltaDDE / deltaOp) * deltaFut;
                        if (opVal > omin)
                        {
                            curDDE.FutCall[3] = fmin + FutNewVal;
                        }
                        else
                        {
                            curDDE.FutCall[3] = fmin - FutNewVal;
                        }

                        opVal = Convert.ToDouble(curDDE.DataItem.PutMHigh);
                        deltaDDE = Math.Abs(opVal - omin);
                        FutNewVal = (deltaDDE / deltaOp) * deltaFut;
                        if (opVal > omin)
                        {
                            curDDE.FutCall[4] = fmin + FutNewVal;
                        }
                        else
                        {
                            curDDE.FutCall[4] = fmin - FutNewVal;
                        }
                    }
                    else if (sideCode == "3")
                    {
                        if (GlobalVar.DayIndex() < 2)
                        {
                            omin = Convert.ToDouble(curDDE.DataItem.PutPreLow);
                            omax = Convert.ToDouble(curDDE.DataItem.PutPreHigh);
                        }
                        double deltaOp = Math.Abs(omax - omin);
                        double opVal = Convert.ToDouble(curDDE.DataItem.CallMLow);
                        double deltaDDE = Math.Abs(opVal - omin);
                        double deltaFut = Math.Abs(fmax - fmin);
                        double FutNewVal = (deltaDDE / deltaOp) * deltaFut;
                        if (deltaOp == 0.0 || deltaFut == 0.0)
                            continue;
                        if (opVal > omin)
                        {
                            curDDE.FutPut[0] = fmax - FutNewVal;
                        }
                        else
                        {
                            curDDE.FutPut[0] = fmax + FutNewVal;
                        }

                        opVal = curDDE.CallJoint;
                        deltaDDE = Math.Abs(opVal - omin);
                        FutNewVal = (deltaDDE / deltaOp) * deltaFut;
                        if (opVal > omin)
                        {
                            curDDE.FutPut[1] = fmax - FutNewVal;
                        }
                        else
                        {
                            curDDE.FutPut[1] = fmax + FutNewVal;
                        }

                        opVal = Convert.ToDouble(curDDE.DataItem.CallBase);
                        deltaDDE = Math.Abs(opVal - omin);
                        FutNewVal = (deltaDDE / deltaOp) * deltaFut;
                        if (opVal > omin)
                        {
                            curDDE.FutPut[2] = fmax - FutNewVal;
                        }
                        else
                        {
                            curDDE.FutPut[2] = fmax + FutNewVal;
                        }

                        opVal = curDDE.CallTarget;
                        deltaDDE = Math.Abs(opVal - omin);
                        FutNewVal = (deltaDDE / deltaOp) * deltaFut;
                        if (opVal > omin)
                        {
                            curDDE.FutPut[3] = fmax - FutNewVal;
                        }
                        else
                        {
                            curDDE.FutPut[3] = fmax + FutNewVal;
                        }

                        opVal = Convert.ToDouble(curDDE.DataItem.CallMHigh);
                        deltaDDE = Math.Abs(opVal - omin);
                        FutNewVal = (deltaDDE / deltaOp) * deltaFut;
                        if (opVal > omin)
                        {
                            curDDE.FutPut[4] = fmax - FutNewVal;
                        }
                        else
                        {
                            curDDE.FutPut[4] = fmax + FutNewVal;
                        }
                    }
                }
            }

            m_DataFilled = true;
        }

        private void SetOptChartData()
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_CPDataSet == null)
                return;
            if (m_CPDataSet.DownLoader.AllOptChartDataDownloaded == false ||
                m_CPDataSet.DownLoader.ATMChanged == false)
                return;
                        
            //m_CenterIndex = m_OpDataSet.FindOptTableIndex(m_CallCode);
            int sCount = FutureSystemChartCtrl.Series.Count;
            for (int i = 1; i < 2; i++)
                FutureSystemChartCtrl.Series[i].Points.Clear();
          
            // 현재 적용가능한 테이블을 찾는다.
            MakeDataTableList();

            m_Max = -999.0;
            m_Min = 999.0;
            // 여기서부터는 옵션 차트 데이터를 넣어 준다.
            for (int i = 1; i < 2; i++)
            {
                if (i <= m_ChartTableList.Count)
                {
                    EasyTrader.DataSet.BarDataTable table = m_ChartTableList[i - 1];
                    if (table.GetRowCount() == 0)
                        continue;

                    FutureSystemChartCtrl.Series[i].Enabled = true;
                    table.Show = true;
                    //FutOptChartCtrl.Series[i].Name = table.TableName;
                    string sideCode = table.TableName.Substring(0, 1);
                    if (sideCode == "2")
                    {
                        if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 3)
                        {
                            FutureSystemChartCtrl.Series[i].Color = Color.Red;
                            SetChartData(table, i);
                        }
                        else
                        {
                            FutureSystemChartCtrl.Series[i].Enabled = false;
                            table.Show = false;
                        }
                    }
                    else
                    {
                        if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 4)
                        {
                            FutureSystemChartCtrl.Series[i].Color = Color.Blue;
                            SetChartData(table, i);
                        }
                        else
                        {
                            FutureSystemChartCtrl.Series[i].Enabled = false;
                            table.Show = false;
                        }
                    }
                }
                else
                {
                    FutureSystemChartCtrl.Series[i].Enabled = false;
                }
            }

            MakeCrossValList();
            MakeDDEValList();

            //SetMinMaxByCross();
            SetMinMaxByDDE();
            //SetFutMinMaxByDDE();

            if (m_Min != 99999 && m_Max != -99999 && m_Max > m_Min)
            {
                FutureSystemChartCtrl.ChartAreas["Price"].AxisY2.Minimum = m_Min;
                FutureSystemChartCtrl.ChartAreas["Price"].AxisY2.Maximum = m_Max;
            }

            if (m_FMin != 99999 && m_FMax != -99999 && m_FMax > m_FMin)
            {
                FutureSystemChartCtrl.ChartAreas["Price"].AxisY.Minimum = m_FMin;
                FutureSystemChartCtrl.ChartAreas["Price"].AxisY.Maximum = m_FMax;
            }
        }




        private void SetMinMaxByDDE()
        {
            //double m_Max = -99999;
            //double m_Min = 99999;

            for (int i = 0; i < m_DDEValList.Count; i++)
            {
                EasyTrader.Option.DDEData curDDE = m_DDEValList[i];

                if (m_Mode == GlobalVar.OpPutMode)
                {
                    if (m_EnableBase == true && IsInSeries(curDDE.PutCode.ToString()) == true)
                    {
                        if (Convert.ToDouble(curDDE.DataItem.CallBase.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallBase.ToString()) > m_Max)
                            m_Max = Convert.ToDouble(curDDE.DataItem.CallBase.ToString());
                        if (Convert.ToDouble(curDDE.DataItem.CallBase.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallBase.ToString()) < m_Min)
                            m_Min = Convert.ToDouble(curDDE.DataItem.CallBase.ToString());
                    }

                    if (m_EnableMonthLow == true && IsInSeries(curDDE.PutCode.ToString()) == true)
                    {
                        if (Convert.ToDouble(curDDE.DataItem.CallMLow.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallMLow.ToString()) > m_Max)
                            m_Max = Convert.ToDouble(curDDE.DataItem.CallMLow.ToString());
                        if (Convert.ToDouble(curDDE.DataItem.CallMLow.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallMLow.ToString()) < m_Min)
                            m_Min = Convert.ToDouble(curDDE.DataItem.CallMLow.ToString());
                    }

                    if (m_EnableMonthHigh == true && IsInSeries(curDDE.PutCode.ToString()) == true)
                    {
                        if (Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString()) > m_Max)
                            m_Max = Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString());
                        if (Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString()) < m_Min)
                            m_Min = Convert.ToDouble(curDDE.DataItem.CallMHigh.ToString());
                    }
                }

                if (m_Mode == GlobalVar.OpCallMode)
                {
                    if (m_EnableBase == true && IsInSeries(curDDE.CallCode.ToString()) == true)
                    {
                        if (Convert.ToDouble(curDDE.DataItem.PutBase.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutBase.ToString()) > m_Max)
                            m_Max = Convert.ToDouble(curDDE.DataItem.PutBase.ToString());
                        if (Convert.ToDouble(curDDE.DataItem.PutBase.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutBase.ToString()) < m_Min)
                            m_Min = Convert.ToDouble(curDDE.DataItem.PutBase.ToString());
                    }

                    if (m_EnableMonthLow == true && IsInSeries(curDDE.CallCode.ToString()) == true)
                    {
                        if (Convert.ToDouble(curDDE.DataItem.PutMLow.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutMLow.ToString()) > m_Max)
                            m_Max = Convert.ToDouble(curDDE.DataItem.PutMLow.ToString());
                        if (Convert.ToDouble(curDDE.DataItem.PutMLow.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutMLow.ToString()) < m_Min)
                            m_Min = Convert.ToDouble(curDDE.DataItem.PutMLow.ToString());
                    }


                    if (m_EnableMonthHigh == true && IsInSeries(curDDE.CallCode.ToString()) == true)
                    {
                        if (Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString()) > m_Max)
                            m_Max = Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString());
                        if (Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString()) != 0.0 && Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString()) < m_Min)
                            m_Min = Convert.ToDouble(curDDE.DataItem.PutMHigh.ToString());
                    }
                }
            }
        }

        private double m_FMax = -99999;
        private double m_FMin = 99999;
        private void SetFutMinMaxByDDE()
        {
            //double m_Max = -99999;
            //double m_Min = 99999;

            for (int i = 0; i < m_FutDDEValList.Count; i++)
            {
                EasyTrader.Option.DDEData curDDE = m_FutDDEValList[i];
                if (m_EnableBase == true)
                {
                    if (curDDE.FutCall[0] != 0.0 && curDDE.FutCall[0] > m_FMax)
                        m_FMax = curDDE.FutCall[0];
                    if (curDDE.FutCall[0] != 0.0 && curDDE.FutCall[0] < m_FMin)
                        m_FMin = curDDE.FutCall[0];
                }

                if (m_EnableMonthLow == true)
                {
                    if (curDDE.FutCall[2] != 0.0 && curDDE.FutCall[2] > m_FMax)
                        m_FMax = curDDE.FutCall[2];
                    if (curDDE.FutCall[2] != 0.0 && curDDE.FutCall[2] < m_FMin)
                        m_FMin = curDDE.FutCall[2];
                }

                if (m_EnableMonthHigh == true)
                {
                    if (curDDE.FutCall[4] != 0.0 && curDDE.FutCall[4] > m_FMax)
                        m_FMax = curDDE.FutCall[4];
                    if (curDDE.FutCall[4] != 0.0 && curDDE.FutCall[4] < m_FMin)
                        m_FMin = curDDE.FutCall[4];
                }


                if (m_EnableBase == true)
                {
                    if (curDDE.FutPut[0] != 0.0 && curDDE.FutPut[0] > m_FMax)
                        m_FMax = curDDE.FutPut[0];
                    if (curDDE.FutPut[0] != 0.0 && curDDE.FutPut[0] < m_FMin)
                        m_FMin = curDDE.FutPut[0];
                }

                if (m_EnableMonthLow == true)
                {
                    if (curDDE.FutPut[2] != 0.0 && curDDE.FutPut[2] > m_FMax)
                        m_FMax = curDDE.FutPut[2];
                    if (curDDE.FutPut[2] != 0.0 && curDDE.FutPut[2] < m_FMin)
                        m_FMin = curDDE.FutPut[2];
                }


                if (m_EnableMonthHigh == true)
                {
                    if (curDDE.FutPut[4] != 0.0 && curDDE.FutPut[4] > m_FMax)
                        m_FMax = curDDE.FutPut[4];
                    if (curDDE.FutPut[4] != 0.0 && curDDE.FutPut[4] < m_FMin)
                        m_FMin = curDDE.FutPut[4];
                }
            }
        }

        private void SetMinMaxByCross()
        {
            //double m_Max = -99999;
            //double m_Min = 99999;
            for (int i = 0; i < m_CrossValList.Count; i++)
            {
                EasyTrader.DataSet.SimpleData curData = m_CrossValList[i];
                // 콜만 표시
                if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 3)
                {
                    /*
                    if (curData.CallVal != 0.0 && curData.CallVal > m_Max)
                    {
                        if (curData.CallType == 0 && m_EnableJoint == true)
                            m_Max = curData.CallVal;
                        if (curData.CallType == 1 && m_EnableTarget == true)
                            m_Max = curData.CallVal;
                    }*/
                    if (curData.PutVal != 0.0)
                    {
                        if (curData.PutType == 0 && m_EnableJoint == true)
                        {
                            if (curData.PutVal > m_Max)
                                m_Max = curData.PutVal;
                            if (curData.PutVal < m_Min)
                                m_Min = curData.PutVal;
                        }
                        if (curData.PutType == 1 && m_EnableTarget == true)
                        {
                            if (curData.PutVal > m_Max)
                                m_Max = curData.PutVal;
                            if (curData.PutVal < m_Min)
                                m_Min = curData.PutVal;
                        }
                    }
                }

                // 풋만 표시
                if (m_ShowType == 0 || m_ShowType == 2 || m_ShowType == 4)
                {
                    if (curData.CallVal != 0.0)
                    {
                        if (curData.CallType == 0 && m_EnableJoint == true)
                        {
                            if (curData.CallVal > m_Max)
                                m_Max = curData.CallVal;
                            if (curData.CallVal < m_Min)
                                m_Min = curData.CallVal;
                        }
                        if (curData.CallType == 1 && m_EnableTarget == true)
                        {
                            if (curData.CallVal > m_Max)
                                m_Max = curData.CallVal;
                            if (curData.CallVal < m_Min)
                                m_Min = curData.CallVal;
                        }
                    }
                }
            }
        }

        private SimpleDataList m_TempList = new SimpleDataList();
        private void MakeCrossValList()
        {
            m_TempList.Clear();

            // 먼저 중심 목표가와 마디가를 가져 온다.
            for (int i = 0; i < m_ChartTableList.Count; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_ChartTableList[i];
                if (table != null)
                {
                    string tableName = table.TableName;
                    string priceCode = tableName.Substring(tableName.Length - 3, 3);
                    m_CPDataSet.FindRecentOptCenterCrossData(m_TempList, priceCode);
                }
            }

            for (int i = 0; i < m_ChartTableList.Count; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_ChartTableList[i];
                if (table != null)
                {
                    string tableName = table.TableName;
                    string priceCode = tableName.Substring(tableName.Length - 3, 3);
                    m_CPDataSet.FindRecentOptOuterCrossData(m_TempList, priceCode);
                }
            }

            m_CrossValList.Clear();
            for (int i = 0; i < m_TempList.Count; i++)
            {
                EasyTrader.DataSet.SimpleData data = m_TempList[i];
                if (data.CallType != -1)
                {
                    if (IsInSeries(data.CallCode) == true)
                    {
                        m_CrossValList.Add(data);
                    }
                }
                if (data.PutType != -1)
                {
                    if (IsInSeries(data.PutCode) == true)
                    {
                        m_CrossValList.Add(data);
                    }
                }
            }
        }

        private bool IsInSeries(string a_Code)
        {
            for (int i = 0; i < m_ChartTableList.Count; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_ChartTableList[i];
                if (table != null)
                {
                    if (table.Show == true && table.TableName == a_Code)
                        return true;
                }
            }

            return false;
        }

        private void MakeDDEValList()
        {
            m_DDEValList.Clear();
            for (int i = 0; i < m_ChartTableList.Count; i++)
            {
                EasyTrader.DataSet.BarDataTable table = m_ChartTableList[i];
                if (table != null)
                {
                    EasyTrader.Option.DDEData curDDE = m_CPDataSet.FindDDEData(m_CPDataSet.DownLoader.CurDay, table.TableName);
                    if (curDDE != null)
                    {
                        m_DDEValList.Add(curDDE);
                    }
                }
            }
        }


        private EasyTrader.Option.DDEData FindDDEVal(string a_TableName, int a_Mode)
        {
            for (int i = 0; i < m_DDEValList.Count; i++)
            {
                EasyTrader.Option.DDEData curDDE = m_DDEValList[i];
                if (a_Mode == GlobalVar.OpCallMode)
                {
                    if (curDDE.CallCode.ToString() == a_TableName)
                        return curDDE;
                }
                else if (a_Mode == GlobalVar.OpPutMode)
                {
                    if (curDDE.PutCode.ToString() == a_TableName)
                        return curDDE;
                }
            }

            return null;
        }

        private EasyTrader.Option.DDEData FindFutDDEVal(string a_TableName)
        {
            for (int i = 0; i < m_FutDDEValList.Count; i++)
            {
                EasyTrader.Option.DDEData curDDE = m_FutDDEValList[i];
                if (curDDE.CallCode.ToString() == a_TableName)
                    return curDDE;
            }

            return null;
        }

        private void SetChartData(EasyTrader.DataSet.BarDataTable dataTable, int a_SeriesIndex)
        {
            if (dataTable == null)
                return;

            int rowCount = dataTable.GetRowCount();
            if (rowCount == 0)
                return;

            double highValue = 0;
            double lowValue = 0;
            double openValue = 0;
            double closeValue = 0;
            for (int i = 0; i < rowCount; i++)
            {
                DataRow row = dataTable.Rows[i];
                try
                {
                    // 값이 없을 경우는 넘어 간다.
                    if (row["고가"] == DBNull.Value)
                        continue;
                    highValue = Convert.ToDouble(row["고가"]);
                    lowValue = Convert.ToDouble(row["저가"]);
                    openValue = Convert.ToDouble(row["시가"]);
                    closeValue = Convert.ToDouble(row["종가"]);
                    if (highValue > m_Max)
                        m_Max = highValue;
                    if (lowValue < m_Min)
                        m_Min = lowValue;

                    string curTime = row["시각"].ToString();
                    string curDate = row["날짜"].ToString();
                    if (i == 0)
                        curTime = "900";
                    //Console.WriteLine(highValue.ToString("F2"));
                    //Console.WriteLine(lowValue.ToString("F2"));
                    //Console.WriteLine(openValue.ToString("F2"));
                    //Console.WriteLine(closeValue.ToString("F2"));
                    int dayIndex = GlobalVar.DayIndex(curTime, m_CPDataSet.DownLoader.OptChartCycle);
                    if (m_CPDataSet.DownLoader.OptChartUnit == 'M' ||
                            m_CPDataSet.DownLoader.OptChartUnit == 'D')
                    {
                        dayIndex = i;
                    }
                    if (curChartType == 0)
                    {
                        FutureSystemChartCtrl.Series[a_SeriesIndex].Points.AddXY(dayIndex, highValue);
                        int pCount = FutureSystemChartCtrl.Series[a_SeriesIndex].Points.Count;
                        FutureSystemChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].XValue = dayIndex;
                        if (m_CPDataSet.DownLoader.OptChartUnit == 'M' ||
                            m_CPDataSet.DownLoader.OptChartUnit == 'D')
                        {
                            FutureSystemChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].AxisLabel = curDate;
                        }
                        else
                            FutureSystemChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].AxisLabel = curTime;
                        FutureSystemChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].YValues[1] = lowValue;
                        FutureSystemChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].YValues[2] = openValue;
                        FutureSystemChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].YValues[3] = closeValue;
                    }
                    else
                    {
                        FutureSystemChartCtrl.Series[a_SeriesIndex].Points.AddXY(dayIndex, closeValue);
                        int pCount = FutureSystemChartCtrl.Series[a_SeriesIndex].Points.Count;
                        FutureSystemChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].XValue = dayIndex;
                        if (m_CPDataSet.DownLoader.OptChartUnit == 'M' ||
                            m_CPDataSet.DownLoader.OptChartUnit == 'D')
                        {
                            FutureSystemChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].AxisLabel = curDate;
                        }
                        else
                            FutureSystemChartCtrl.Series[a_SeriesIndex].Points[pCount - 1].AxisLabel = curTime;
                    }

                    m_DataFilled = true;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }

        private void SetChartData()
        {
            // 데이터 셋 객체가 없으면 아무일도 하지 않는다.
            if (m_CPDataSet == null || GlobalVar.FutOptChartDataDownloaded == false)
                return;

            FutureSystemChartCtrl.Series["지수"].Points.Clear();
            FutureSystemChartCtrl.Series["최고"].Points.Clear();
            FutureSystemChartCtrl.Series["최저"].Points.Clear();
            FutureSystemChartCtrl.Series["상위"].Points.Clear();
            FutureSystemChartCtrl.Series["하위"].Points.Clear();
            //FutureSystemChartCtrl.Series["기준가"].Points.Clear();
            EasyTrader.DataSet.FutOptChartTable dataTable = m_CPDataSet.GetFutOptChartTable();
            if (dataTable == null)
                return;

            //double maxValue = -10000.0;
            //double minValue = 10000.0;
            int rowCount = dataTable.GetRowCount();
            double highValue = 0;
            double lowValue = 0;
            double openValue = dataTable.GetOpenVal();
            double closeValue = 0;
            double stdVal = m_CPDataSet.FindTodayBase();
            /*
            // 시작값이 있을 때는 시작값을 설정해 준다.
            if (openValue != 0)
            {
                if (curChartType == 0)
                {
                    FutureSystemChartCtrl.Series["지수"].Points.AddXY(0, openValue);
                    FutureSystemChartCtrl.Series["지수"].Points[0].XValue = 0;
                    FutureSystemChartCtrl.Series["지수"].Points[0].AxisLabel = "900";
                    FutureSystemChartCtrl.Series["지수"].Points[0].YValues[1] = openValue;
                    FutureSystemChartCtrl.Series["지수"].Points[0].YValues[2] = openValue;
                    FutureSystemChartCtrl.Series["지수"].Points[0].YValues[3] = openValue;
                }
                else
                {
                    FutureSystemChartCtrl.Series["지수"].Points.AddXY(0, openValue);
                    FutureSystemChartCtrl.Series["지수"].Points[0].XValue = 0;
                    FutureSystemChartCtrl.Series["지수"].Points[0].AxisLabel = "900";
                }
            }*/
            for (int i = 0; i < rowCount; i++)
            {
                DataRow row = dataTable.Rows[i];
                try
                {
                    // 값이 없을 경우는 넘어 간다.
                    if (row["종가"] == DBNull.Value)
                        continue;
                    closeValue = Convert.ToDouble(row["종가"]);
                    // 값이 0이라는 것은 값을 얻어오지 못했다는 것이므로 여기서 그만한다.
                    if (closeValue == 0)
                        continue;

                    highValue = Convert.ToDouble(row["고가"]);
                    lowValue = Convert.ToDouble(row["저가"]);
                    openValue = Convert.ToDouble(row["시가"]);
                    if (i == 0)
                    {
                        m_FMax = highValue;
                        m_FMin = lowValue;
                    }
                    if (curChartType == 0)
                    {
                        FutureSystemChartCtrl.Series["지수"].Points.AddXY(i, highValue);
                        FutureSystemChartCtrl.Series["지수"].Points[i].XValue = i;
                        FutureSystemChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                        FutureSystemChartCtrl.Series["지수"].Points[i].YValues[1] = lowValue;
                        FutureSystemChartCtrl.Series["지수"].Points[i].YValues[2] = openValue;
                        FutureSystemChartCtrl.Series["지수"].Points[i].YValues[3] = closeValue;
                    }
                    else
                    {
                        FutureSystemChartCtrl.Series["지수"].Points.AddXY(i, closeValue);
                        FutureSystemChartCtrl.Series["지수"].Points[i].XValue = i;
                        FutureSystemChartCtrl.Series["지수"].Points[i].AxisLabel = row["시각"].ToString();
                    }

                    if (highValue != 0 && highValue > m_FMax)
                    {
                        m_FMax = highValue;
                    }
                    if (lowValue != 0 && lowValue < m_FMin)
                    {
                        m_FMin = lowValue;
                    }

                    FutureSystemChartCtrl.Series["최저"].Points.AddXY(i, m_FMin);
                    FutureSystemChartCtrl.Series["최고"].Points.AddXY(i, m_FMax);

                    double dayHeight = m_FMax - m_FMin;
                    double highZone = m_FMax - dayHeight * GlobalVar.HighLowPercent;
                    double lowZone = m_FMin + dayHeight * GlobalVar.HighLowPercent;

                    FutureSystemChartCtrl.Series["상위"].Points.AddXY(i, highZone);
                    FutureSystemChartCtrl.Series["하위"].Points.AddXY(i, lowZone);
                    //FutureSystemChartCtrl.Series["기준가"].Points.AddXY(i, stdVal);
                    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            /*
            if (stdVal != 0 && stdVal > maxValue)
            {
                maxValue = stdVal;
            }
            if (stdVal != 0 && stdVal < minValue)
            {
                minValue = stdVal;
            }*/

            double valueHeight = m_FMax - m_FMin;
            double ceilVal = Math.Ceiling(valueHeight);
            m_FMax = m_FMin + ceilVal;

            
            SetFutMinMaxByDDE();

            double fmin = 0.0, fmax = 0.0;
            GlobalVar.FindMinMax(dataTable, 0, GlobalVar.DayIndex(), ref fmin, ref fmax);
            if (m_FMax > fmax + 1.0)
                m_FMax = fmax + 1.0;
            if (m_FMin < fmin - .10)
                m_FMin = fmin - 1.0;

            if (m_FMax >= m_FMin)
            {
                FutureSystemChartCtrl.ChartAreas["Price"].AxisY.Minimum = m_FMin;
                FutureSystemChartCtrl.ChartAreas["Price"].AxisY.Maximum = m_FMax;
            }
        }

        public FutureSystemFrm(ETDataSet a_DataSet)
        {
            InitializeComponent();
            m_CPDataSet = a_DataSet;
            InitControl();


            //m_CPDataSet.CreateDDEData();

           
            m_CenterIndex = GlobalVar.OptChartRange;
        }

        private void InitChart()
        {
            FutureSystemChartCtrl.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(211)), ((System.Byte)(223)), ((System.Byte)(240)));
            FutureSystemChartCtrl.BackSecondaryColor = System.Drawing.Color.White;
            FutureSystemChartCtrl.BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            FutureSystemChartCtrl.BorderlineColor = System.Drawing.Color.FromArgb(((System.Byte)(26)), ((System.Byte)(59)), ((System.Byte)(105)));
            FutureSystemChartCtrl.BorderlineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            FutureSystemChartCtrl.BorderlineWidth = 2;
            FutureSystemChartCtrl.BorderSkin.SkinStyle = System.Windows.Forms.DataVisualization.Charting.BorderSkinStyle.Emboss;

            FutureSystemChartCtrl.ChartAreas["Price"].AxisX.MajorGrid.Interval = 10;
            FutureSystemChartCtrl.ChartAreas["Price"].AxisX.Interval = 10;
            FutureSystemChartCtrl.ChartAreas["Price"].AxisY.MajorGrid.Interval = 1;
            FutureSystemChartCtrl.ChartAreas["Price"].AxisY.Interval = 1;

            FutureSystemChartCtrl.ChartAreas["Price"].Area3DStyle.IsClustered = true;
            FutureSystemChartCtrl.ChartAreas["Price"].Area3DStyle.Perspective = 10;
            FutureSystemChartCtrl.ChartAreas["Price"].Area3DStyle.IsRightAngleAxes = false;
            FutureSystemChartCtrl.ChartAreas["Price"].Area3DStyle.WallWidth = 0;
            FutureSystemChartCtrl.ChartAreas["Price"].Area3DStyle.Inclination = 15;
            FutureSystemChartCtrl.ChartAreas["Price"].Area3DStyle.Rotation = 10;
            FutureSystemChartCtrl.ChartAreas["Price"].AxisX.IsLabelAutoFit = true;
            FutureSystemChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            FutureSystemChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.IsEndLabelVisible = false;
            FutureSystemChartCtrl.ChartAreas["Price"].AxisX.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutureSystemChartCtrl.ChartAreas["Price"].AxisX.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutureSystemChartCtrl.ChartAreas["Price"].AxisY.IsLabelAutoFit = true;
            FutureSystemChartCtrl.ChartAreas["Price"].AxisY.LabelStyle.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold);
            FutureSystemChartCtrl.ChartAreas["Price"].AxisY.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutureSystemChartCtrl.ChartAreas["Price"].AxisY.MajorGrid.LineColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutureSystemChartCtrl.ChartAreas["Price"].AxisY.IsStartedFromZero = false;
            //FutureSystemChartCtrl.ChartAreas["Price"].AxisY.LabelAutoFitMaxFontSize;
            FutureSystemChartCtrl.ChartAreas["Price"].BackColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(165)), ((System.Byte)(191)), ((System.Byte)(228)));
            FutureSystemChartCtrl.ChartAreas["Price"].BackSecondaryColor = System.Drawing.Color.White;
            FutureSystemChartCtrl.ChartAreas["Price"].BackGradientStyle = System.Windows.Forms.DataVisualization.Charting.GradientStyle.TopBottom;
            FutureSystemChartCtrl.ChartAreas["Price"].BorderColor = System.Drawing.Color.FromArgb(((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)), ((System.Byte)(64)));
            FutureSystemChartCtrl.ChartAreas["Price"].BorderDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Solid;
            FutureSystemChartCtrl.ChartAreas["Price"].Position.Auto = true;
            //FutureSystemChartCtrl.ChartAreas["Price"].Position.Height = 80F;
            //FutureSystemChartCtrl.ChartAreas["Price"].Position.Width = 80F;
            //FutureSystemChartCtrl.ChartAreas["Price"].Position.X = 5F;
            //FutureSystemChartCtrl.ChartAreas["Price"].Position.Y = 10F;
            FutureSystemChartCtrl.ChartAreas["Price"].ShadowColor = System.Drawing.Color.Transparent;
            DateTime now = DateTime.Now;
            if (now.Year == GlobalVar.YearLimit && now.Month >= GlobalVar.MonthLimit)
            {
                FutureSystemChartCtrl.ChartAreas["Price"].BackImage = "Credential.jpg";
                FutureSystemChartCtrl.ChartAreas["Price"].BackImageAlignment = ChartImageAlignmentStyle.Right;
            }
            if (GlobalVar.FutureSystemChartType == 0)
            {
                FutureSystemChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Candlestick;
                comboFutureSystemChartType.SelectedIndex = 0;
            }
            else
            {
                FutureSystemChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                comboFutureSystemChartType.SelectedIndex = 1;
            }

            FutureSystemChartCtrl.Series["지수"]["PriceUpColor"] = "Red";
            FutureSystemChartCtrl.Series["지수"]["PriceDownColor"] = "Blue";
            FutureSystemChartCtrl.ChartAreas["Price"].AxisX.LabelStyle.IsEndLabelVisible = true;
            FutureSystemChartCtrl.ChartAreas["Price"].AxisX.IsMarginVisible = true;
            FutureSystemChartCtrl.ChartAreas["Price"].AxisY.LabelStyle.IsEndLabelVisible = true;
            FutureSystemChartCtrl.ChartAreas["Price"].AxisY.IsMarginVisible = true;
            //FutureSystemChartCtrl.Series[0].Color = Color.Red;
            //DataPointCustomProperties aa = FutureSystemChartCtrl.Series[0]["PriceUpColor"];
        }

        private void FutureSystemFrm_Load(object sender, EventArgs e)
        {
            InitChart();
            InitTimer();
            curChartType = GlobalVar.FutOptChartType;
            m_WaveManager.EasyTraderDataSet = m_CPDataSet;
            m_SysName = GlobalVar.SysNameArray[m_SysType];
            this.Text = m_SysName;

            // 이벤트 핸들러를 등록해 준다.
            m_TotalSignalManager.LastSignalFired += new SysManagerEventHandler(this.SysManager_OnLastSignalFired);
        }

        private void FutureSystemFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer.Stop();
        }

        private void comboFutureSystemChartType_SelectedIndexChanged(object sender, EventArgs e)
        {
            curChartType = comboFutureSystemChartType.SelectedIndex;
            if (curChartType != -1)
            {
                if (curChartType == 0)
                {
                    FutureSystemChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Candlestick;
                    FutureSystemChartCtrl.Series["옵션"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Candlestick;
                }
                else
                {
                    FutureSystemChartCtrl.Series["지수"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                    FutureSystemChartCtrl.Series["옵션"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
                }
                SetChartData();
                FutureSystemChartCtrl.Invalidate();
            }
        }

        private void cbShowWave_CheckedChanged(object sender, EventArgs e)
        {
            if (cbShowWave.Checked)
            {
                FutureSystemChartCtrl.Series["파동"].Enabled = true;
            }
            else
            {
                FutureSystemChartCtrl.Series["파동"].Enabled = false;
            }
        }

        private void cbShowPrice_CheckedChanged(object sender, EventArgs e)
        {
            Series series = FutureSystemChartCtrl.Series.FindByName("지수");
            if (series == null)
                return;
            if (cbShowPrice.Checked == true)
            {
                FutureSystemChartCtrl.Series["지수"].IsValueShownAsLabel = true;
                FutureSystemChartCtrl.Series["지수"].Label = "#VALX : #VAL{G5}";
            }
            else
            {
                FutureSystemChartCtrl.Series["지수"].IsValueShownAsLabel = false;
                FutureSystemChartCtrl.Series["지수"].Label = "";
            }
        }

        private void cbZoom_CheckedChanged(object sender, EventArgs e)
        {
            if (cbZoom.Checked)
            {
                FutureSystemChartCtrl.EnableZoomAndPanControls(ChartCursorSelected, ChartCursorMoved);
            }
            else
            {
                FutureSystemChartCtrl.DisableZoomAndPanControls();
            }
        }

        private void cbForecasting_CheckedChanged(object sender, EventArgs e)
        {
            /*
            if (cbForecasting.Checked == true)
            {
                labelReferenceRange.Enabled = true;
                nudReferenceRange.Enabled = true;
                FutureSystemChartCtrl.Series["Forecasting"].Enabled = true;
                FutureSystemChartCtrl.Series["ErrorRange"].Enabled = true;
            }
            else
            {
                labelReferenceRange.Enabled = false;
                nudReferenceRange.Enabled = false;
                FutureSystemChartCtrl.Series["Forecasting"].Enabled = false;
                FutureSystemChartCtrl.Series["ErrorRange"].Enabled = false;
            }*/
        }

        private void nudReferenceRange_ValueChanged(object sender, EventArgs e)
        {
            /*
            GlobalVar.PriceReferenceRange = (int)nudReferenceRange.Value;

            string regSubkey = "Software\\EasyTrader\\Operation";
            // 서브키를 얻어온다. 없으면 null
            RegistryKey rk = Registry.CurrentUser.OpenSubKey(regSubkey, true);
            // 없으면 서브키를 만든다.
            if (rk == null)
            {
                // 해당이름으로 서브키 생성
                rk = Registry.CurrentUser.CreateSubKey(regSubkey);
            }

            // 서브키 아래 값 쓰기
            rk.SetValue("PriceReferenceRange", GlobalVar.PriceReferenceRange.ToString());
             */
        }

        private void cbPrice_CheckedChanged(object sender, EventArgs e)
        {
            Series series = FutureSystemChartCtrl.Series["지수"];
            if (series == null)
                return;
            if (cbPrice.Checked)
            {
                series.Enabled = true;
            }
            else
            {
                series.Enabled = false;
            }
        }

        private void cbMax_CheckedChanged(object sender, EventArgs e)
        {
            Series series = FutureSystemChartCtrl.Series["최고"];
            if (series == null)
                return;
            
        }

        private void cbMin_CheckedChanged(object sender, EventArgs e)
        {
            Series series = FutureSystemChartCtrl.Series["최저"];
            if (series == null)
                return;
            
        }

        private void cbHigh_CheckedChanged(object sender, EventArgs e)
        {
            Series series = FutureSystemChartCtrl.Series["상위"];
            if (series == null)
                return;
            if (cbHigh.Checked)
            {
                series.Enabled = true;
            }
            else
            {
                series.Enabled = false;
            }
        }

        private void cbLow_CheckedChanged(object sender, EventArgs e)
        {
            Series series = FutureSystemChartCtrl.Series["하위"];
            if (series == null)
                return;
            if (cbLow.Checked)
            {
                series.Enabled = true;
            }
            else
            {
                series.Enabled = false;
            }
        }

        private void btnLiquidAll_Click(object sender, EventArgs e)
        {
            if (m_ETOrderManager != null)
            {
                GlobalVar.WriteLog("시스템창에서 모두 청산을 부름");
                // 일단 모든 주문을 청산시켜 준다.
                m_ETOrderManager.LiquidAll();
                // 각시스템의 자동 주문을 현재 선택에 시스템에 맞게 해제시켜 준다.
                if (m_TotalSignalManager != null)
                {
                    if (m_SysType == GlobalVar.SysTypeJisuWaveHogaSummit)
                    {
                        JisuWaveHogaSummitSysVar.AutoOrder = false;
                        JisuWaveHogaSummitSysVar.LastSignalFired = true;
                        m_TotalSignalManager.FireLastSignal(false, m_SysType);
                    }
                    else if (m_SysType == GlobalVar.SysTypeJisuWave)
                    {
                        JisuWaveSysVar.AutoOrder = false;
                        JisuWaveSysVar.LastSignalFired = true;
                        m_TotalSignalManager.FireLastSignal(false, m_SysType);
                    }
                    else if (m_SysType == GlobalVar.SysTypeHogaWave)
                    {
                        HogaWaveSysVar.AutoOrder = false;
                        HogaWaveSysVar.LastSignalFired = true;
                        m_TotalSignalManager.FireLastSignal(false, m_SysType);
                    }
                    else if (m_SysType == GlobalVar.SysTypeHogaSquareOcc)
                    {
                        HogaSquareOccSysVar.AutoOrder = false;
                        HogaSquareOccSysVar.LastSignalFired = true;
                        m_TotalSignalManager.FireLastSignal(false, m_SysType);
                    }
                    else if (m_SysType == GlobalVar.SysTypeHogaSummit)
                    {
                         HogaSummitSysVar.AutoOrder = false;
                         HogaSummitSysVar.LastSignalFired = true;
                         m_TotalSignalManager.FireLastSignal(false, m_SysType);
                    }
                    else if (m_SysType == GlobalVar.SysTypeCallPutSquareOcc)
                    {
                        CallPutSquareOccSysVar.AutoOrder = false;
                        CallPutSquareOccSysVar.LastSignalFired = true;
                        m_TotalSignalManager.FireLastSignal(false, m_SysType);
                    }
                    else if (m_SysType == GlobalVar.SysTypePureHogaSummit)
                    {
                        PureHogaSummitSysVar.AutoOrder = false;
                        PureHogaSummitSysVar.LastSignalFired = true;
                        m_TotalSignalManager.FireLastSignal(false, m_SysType);
                    }
                    else if (m_SysType == GlobalVar.SysTypeLooseHogaSummit)
                    {
                        LooseHogaSummitSysVar.AutoOrder = false;
                        LooseHogaSummitSysVar.LastSignalFired = true;
                        m_TotalSignalManager.FireLastSignal(false, m_SysType);
                    }
                    else if (m_SysType == GlobalVar.SysTypeCallPutInvDiv)
                    {
                         CallPutInvDivSysVar.AutoOrder = false;
                         CallPutInvDivSysVar.LastSignalFired = true;
                         m_TotalSignalManager.FireLastSignal(false, m_SysType);
                    }
                    else if (m_SysType == GlobalVar.SysTypeTipAttack)
                    {
                        TipAttackSysVar.AutoOrder = false;
                        TipAttackSysVar.LastSignalFired = true;
                        m_TotalSignalManager.FireLastSignal(false, m_SysType);
                    }
                    else if (m_SysType == GlobalVar.SysTypeOptPrice)
                    {
                        OptPriceSysVar.AutoOrder = false;
                        OptPriceSysVar.LastSignalFired = true;
                        m_TotalSignalManager.FireLastSignal(false, m_SysType);
                    }
                }
            }
        }

        

        private void cbAutoOrder_CheckedChanged(object sender, EventArgs e)
        {
            string selText = "";
            bool autoOrder = false;
            if (cbAutoOrder.Checked == true)
            {
                m_ETOrderManager.InitOrder();
                selText = "True";
                autoOrder = true;
            }
            else
            {
                selText = "False";
                autoOrder = false;
            }

            string regSubkey = "Software\\EasyTrader\\SysVar\\JisuWaveHogaSummitSysVar";
            if (m_SysType == GlobalVar.SysTypeJisuWaveHogaSummit)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\JisuWaveHogaSummitSysVar";
                JisuWaveHogaSummitSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeJisuWave)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\JisuWaveSysVar";
                JisuWaveSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaWave)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\HogaWaveSysVar";
                HogaWaveSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSquareOcc)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\HogaSquareOccSysVar";
                HogaSquareOccSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSummit)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\HogaSummitSysVar";
                HogaSummitSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeCallPutSquareOcc)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\CallPutSquareOccSysVar";
                CallPutSquareOccSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypePureHogaSummit)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\PureHogaSummitSysVar";
                PureHogaSummitSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeLooseHogaSummit)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\LooseHogaSummitSysVar";
                LooseHogaSummitSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeCallPutInvDiv)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\CallPutInvDivSysVar";
                CallPutInvDivSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeTipAttack)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\TipAttackSysVar";
                TipAttackSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeOptPrice)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\OptPriceSysVar";
                OptPriceSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeOptMainPrice)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\OptMainPriceSysVar";
                OptMainPriceSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeOptCenterPrice)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\OptCenterPriceSysVar";
                OptCenterPriceSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeOptBothSell)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\OptBothSellSysVar";
                OptBothSellSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeOptBend)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\OptBendSysVar";
                OptBendSysVar.AutoOrder = autoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeSubject)
            {
                regSubkey = "Software\\EasyTrader\\SysVar\\SubjectSysVar";
                SubjectSysVar.AutoOrder = autoOrder;
            }

            RegistryKey rk = Registry.CurrentUser.OpenSubKey(regSubkey, true);
            // 없으면 서브키를 만든다.
            if (rk == null)
            {
                // 해당이름으로 서브키 생성
                rk = Registry.CurrentUser.CreateSubKey(regSubkey);
            }

            // 서브키 아래 값 쓰기
            rk.SetValue("AutoOrder", selText);
        }

        private void FutureSystemChartCtrl_PostPaint(object sender, ChartPaintEventArgs e)
        {
            if (m_TotalSignalManager == null)
                return;

            bool LastSignalFired = m_TotalSignalManager.FindLastSignalFired(m_SysType);
            if (LastSignalFired == true)
            {
                if (m_ShowSignal == true || m_ShowStateList == true)
                {
                    PriceSignalList signalList = m_TotalSignalManager.SysManagerList[m_SysType].PriceStateList;
                    DrawSignal(signalList, e);
                }
            }
            else
            {
                if (m_ShowSignal == true)
                {
                    PriceSignalList signalList = m_TotalSignalManager.SysManagerList[m_SysType].PriceSignalList;
                    DrawSignal(signalList, e);
                }

                if (m_ShowStateList == true)
                {
                    PriceSignalList signalList = m_TotalSignalManager.SysManagerList[m_SysType].PriceStateList;
                    DrawSignal(signalList, e);
                }
            }

            DateTime now = DateTime.Now;
            if (now.Year == GlobalVar.YearLimit && now.Month >= GlobalVar.MonthLimit)
            {
                DrawCredential(e);
            }

            if (m_ShowOption == true)
                DrawOpVal(e);

            if (m_DataFilled == true)
            {
                //DrawOpDDEPrice(e);
                DrawFutDDEPrice(e);
                //DrawCrossPrice(e);
            }
        }

        private void DrawCredential(ChartPaintEventArgs a_EventArg)
        {
            if (a_EventArg.ChartElement is ChartArea)
            {
                ChartArea area = (ChartArea)a_EventArg.ChartElement;
                if (area.Name == "Price")
                {
                    double highXValue = 0;
                    double highYValue = 0;

                    Graphics graphics = a_EventArg.ChartGraphics.Graphics;

                    Font myFont = new Font(FontFamily.GenericSansSerif, 9,
                    FontStyle.Regular);

                    System.Drawing.StringFormat format = new System.Drawing.StringFormat();
                    // Set the TextRenderingHint property.
                    graphics.TextRenderingHint =
                        System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
                    string msg = GlobalVar.CopyWriteMsg + "\n" + GlobalVar.Name + "\n" + GlobalVar.HP + "\n" + GlobalVar.EMail;


                    // Convert X and Y values to screen position
                    float pixelYMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.Y, highYValue);
                    float pixelXMax = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.X, highXValue);
                    float pixelYMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.Y, highYValue);
                    float pixelXMin = (float)a_EventArg.ChartGraphics.GetPositionFromAxis("Price", AxisName.X, highXValue);

                    // Draw the string.
                    graphics.DrawString(msg, myFont,
                        Brushes.Blue, pixelXMin, pixelYMin);

                }
            }
        }

        private bool m_ShowSignal = true;
        private void cbShowSignal_CheckedChanged(object sender, EventArgs e)
        {
            if (cbShowSignal.Checked)
                m_ShowSignal = true;
            else
                m_ShowSignal = false;
        }

        private void cbCurWaveReg_CheckedChanged(object sender, EventArgs e)
        {
            /*
            if (cbCurWaveReg.Checked)
            {
                FutureSystemChartCtrl.Series["현재평균파"].Enabled = true;
            }
            else
            {
                FutureSystemChartCtrl.Series["현재평균파"].Enabled = false;
            }*/
        }

        private void cbSigWaveReg_CheckedChanged(object sender, EventArgs e)
        {
            /*
            if (cbSigWaveReg.Checked)
            {
                FutureSystemChartCtrl.Series["신호평균파"].Enabled = true;
            }
            else
            {
                FutureSystemChartCtrl.Series["신호평균파"].Enabled = false;
            }*/
        }

        private void comboSystem_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboSystem.SelectedIndex < 0)
                m_SysType = 0;
            else
                m_SysType = comboSystem.SelectedIndex;
            m_SysName = GlobalVar.SysNameArray[m_SysType];
            this.Text = m_SysName;
            bool autoOrder = false;
            /*
            if (m_SysType == 0)
            {
                autoOrder = JisuWaveHogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == 1)
            {
                autoOrder = JisuWaveSysVar.AutoOrder;
            }
            else if (m_SysType == 2)
            {
                autoOrder = HogaWaveSysVar.AutoOrder;
            }
            else if (m_SysType == 3)
            {
                autoOrder = HogaSquareOccSysVar.AutoOrder;
            }
            else if (m_SysType == 4)
            {
                autoOrder = HogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == 5)
            {
                autoOrder = CallPutSquareOccSysVar.AutoOrder;
            }
            else if (m_SysType == 6)
            {
                autoOrder = PureHogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == 7)
            {
                autoOrder = LooseHogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == 8)
            {
                autoOrder = CallPutInvDivSysVar.AutoOrder;
            }
            else if (m_SysType == 9)
            {
                autoOrder = TipAttackSysVar.AutoOrder;
            }
            else if (m_SysType == 10)
            {
                autoOrder = OptPriceSysVar.AutoOrder;
            }
             */
            if (m_SysType == GlobalVar.SysTypeJisuWaveHogaSummit)
            {
                autoOrder = JisuWaveHogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeJisuWave)
            {
                autoOrder = JisuWaveSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaWave)
            {
                autoOrder = HogaWaveSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSquareOcc)
            {
                autoOrder = HogaSquareOccSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSummit)
            {
                autoOrder = HogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeCallPutSquareOcc)
            {
                autoOrder = CallPutSquareOccSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypePureHogaSummit)
            {
                autoOrder = PureHogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeLooseHogaSummit)
            {
                autoOrder = LooseHogaSummitSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeCallPutInvDiv)
            {
                autoOrder = CallPutInvDivSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeTipAttack)
            {
                autoOrder = TipAttackSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeOptPrice)
            {
                autoOrder = OptPriceSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeOptMainPrice)
            {
                autoOrder = OptMainPriceSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeOptCenterPrice)
            {
                autoOrder = OptCenterPriceSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeOptBothSell)
            {
                autoOrder = OptBothSellSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeOptBend)
            {
                autoOrder = OptBendSysVar.AutoOrder;
            }
            else if (m_SysType == GlobalVar.SysTypeSubject)
            {
                autoOrder = SubjectSysVar.AutoOrder;
            }

            if (autoOrder == true)
            {
                cbAutoOrder.Checked = true;
            }
            else
            {
                cbAutoOrder.Checked = false;
            }
        }

        private void btnSysSet_Click(object sender, EventArgs e)
        {
            if (m_SysType == GlobalVar.SysTypeJisuWaveHogaSummit)
            {
                EasyTrader.Form.JisuWaveHogaSummitSysSetFrm signalSettingFrm = new EasyTrader.Form.JisuWaveHogaSummitSysSetFrm();
                signalSettingFrm.Show();
            }
            else if (m_SysType == GlobalVar.SysTypeJisuWave)
            {
                EasyTrader.Form.JisuWaveSysSetFrm signalSettingFrm = new EasyTrader.Form.JisuWaveSysSetFrm();
                signalSettingFrm.Show();
            }
            else if (m_SysType == GlobalVar.SysTypeHogaWave)
            {
                EasyTrader.Form.HogaWaveSysSetFrm signalSettingFrm = new EasyTrader.Form.HogaWaveSysSetFrm();
                signalSettingFrm.Show();
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSquareOcc)
            {
                EasyTrader.Form.HogaSquareOccSysSetFrm signalSettingFrm = new EasyTrader.Form.HogaSquareOccSysSetFrm();
                signalSettingFrm.Show();
            }
            else if (m_SysType == GlobalVar.SysTypeHogaSummit)
            {
                EasyTrader.Form.HogaSummitSysSetFrm signalSettingFrm = new EasyTrader.Form.HogaSummitSysSetFrm();
                signalSettingFrm.Show();
            }
            else if (m_SysType == GlobalVar.SysTypeCallPutSquareOcc)
            {
                EasyTrader.Form.CallPutSquareOccSysSetFrm signalSettingFrm = new EasyTrader.Form.CallPutSquareOccSysSetFrm();
                signalSettingFrm.Show();
            }
        }

        private void comboFirstSignal_SelectedIndexChanged(object sender, EventArgs e)
        {
            ;
        }

        private void btnFirstSigSet_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.Form frmchild = new EasyTrader.Form.FirstSigSetFrm();
            frmchild.Show();
        }

        private bool m_ShowStateList = false;
        private void cbShowStateList_CheckedChanged(object sender, EventArgs e)
        {
            if (cbShowStateList.Checked == true)
                m_ShowStateList = true;
            else
                m_ShowStateList = false;
        }

        private void cbShowOption_CheckedChanged(object sender, EventArgs e)
        {
            if (cbShowOption.Checked == true)
                m_ShowOption = true;
            else
                m_ShowOption = false;
        }
    }
}
